﻿
Imports System
Imports System.Collections.Generic
Imports System.Windows.Forms

Imports org.codegen.common.ProgressIndicator
Imports CrystalReportViewer
Imports IICBusinessLogic
Imports IICBusinessLogic.PeriodProcessing
Imports System.ComponentModel


Imports System.Threading
Imports org.codegen.common.Encryption


Namespace My

    ' The following events are available for MyApplication:
    ' 
    ' Startup: Raised when the application starts, before the startup form is created.
    ' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
    ' UnhandledException: Raised if the application encounters an unhandled exception.
    ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
    ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
    Partial Friend Class MyApplication


        Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup

            ModelContext.newCurrent(Environment.UserName, Nothing)

            'add global validator to ClassMember so all instances of ClassMember in the 
            'application automatically get this validator
            ModelContext.Current.addGlobalModelValidator( _
                GetType(ClassMember), GetType(UIGradeChangedValidator))

            'FormsApplicationContext.current.Translator = ILanguageStrings.getFromConfig
            FormsApplicationContext.current.SaveOnEnterKey = False
            FormsApplicationContext.current.ApplicationDefaultCasing = CharacterCasing.Upper
            FormsApplicationContext.current.ApplicationDefaultFont = _
                    New System.Drawing.Font("Verdana", 9.0!, System.Drawing.FontStyle.Regular, _
                                System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            FormsApplicationContext.current.MarkMandatoryFieldsWithAsterisk = True
            WinEventLogger.cEventSource = "IIC Management System"

            Dim backupSql = <backupSql>
BACKUP DATABASE [iicdb] 
TO  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\Backup\iicdbUpgradeFrom{0}To{1}.bak'
WITH NOFORMAT, INIT,  NAME = N'iicdb-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
</backupSql>

            DBUpdater.dbUpdateVersion(DBUtils.Current, DBVersion.SYSTEM_DATABASE_VERSION, _
                                      GetType(IICModel.BusObjects.Lesson).Assembly, backupSql.Value)

            'My.Settings.ftpRemotePassword = SimpleEncrypt.Cipher("iic2012*")
            'My.Settings.ftpRemoteUser = SimpleEncrypt.Cipher("members")
            'My.Settings.ftphost = SimpleEncrypt.Cipher("194.30.133.100") 'iic.org.cy
            'My.Settings.ftpBackupDir = SimpleEncrypt.Cipher("/")

            'My.Settings.dbBackupDir = SimpleEncrypt.Cipher("C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\Backup\")
            'My.Settings.dbName = "iicdb"
            'My.Settings.dbLastBackupDate = "01012000"
            ' My.Settings.dbOnlineBackupLocation = SimpleEncrypt.Cipher("http://www.iic.org.cy/IICMembersSystem/iicdb.bak.zip")

            'If My.Settings.dasUpdatedDone = 0 Then
            '    Me.updateDAS()
            'End If
            If My.Settings.pvakMapsUpdate = 0 Then
                Call pvakMapsUpdate()
            End If
        End Sub


        Private Sub updateDAS()

            ModelContext.newCurrent(Environment.UserName, Nothing)

            Try
                ModelContext.beginTrans()

                Dim d As New DataConversion.DASUpdate
                d.reverseAllDASPeriods()

                Dim dsm As New IICBusinessLogic.PasDasStructureManager()
                dsm.updateDASStructure()
                d.processDASPeriods()
                My.Settings.dasUpdatedDone = 1

                ModelContext.commitTrans()
            Finally
                ModelContext.rollbackTrans()
            End Try

        End Sub

        ''' <summary>
        ''' Log all unhandled exceptions to the windows event log
        ''' </summary>
        Private Sub MyApplication_UnhandledException(ByVal sender As Object, _
                ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) _
                Handles Me.UnhandledException

            MsgBox(e.Exception.Message, MsgBoxStyle.Exclamation, _
                        FormsApplicationContext.current.ApplicationTitle)

            Call WinEventLogger.WriteError(e.Exception)

        End Sub


        ''' <summary>
        ''' After the reports are loaded, they are kept in memory using this variable
        ''' </summary>
        ''' <remarks></remarks>
        Private _reportsCache As XMLResourceReportDefinitionsProvider

        Public ReadOnly Property reportsCache As XMLResourceReportDefinitionsProvider
            Get
                If _reportsCache Is Nothing Then
                    _reportsCache = New XMLResourceReportDefinitionsProvider()
                    _reportsCache.setFileOrResourceName("IIC.ReportDefinitions.xml")

                End If
                Return _reportsCache
            End Get

        End Property

        Private Sub pvakMapsUpdate()

            Dim lst As List(Of PeriodClass) = PeriodClassDataUtils.findList("PeriodId in (112,118)")
            For Each pc As PeriodClass In lst
                If pc.GradeMappings.Count = 0 Then
                    Call GradeMappingUtils.copyMappingsFromPreviousPeriods(pc)
                    pc.isDirty = True
                    PeriodClassDataUtils.savePeriodClass(pc)
                End If

            Next
            My.Settings.pvakMapsUpdate = 1
        End Sub



    End Class
End Namespace
